const sqluser = require('./sqlPromise');
const $sql = require('../db/sqlMap');
const jwt = require('jsonwebtoken');

const SECRET = "2508tqdhckyxbnwjdhstqdnb"

function sep() {
    console.log('\n'+'*'.repeat(50)+'\n');
}

// 中间件：验证授权
const auth = (req, res, next) => {
	try{
		let author = req.headers.authorization;
		if(author == undefined || author.length == 0){
			throw new Error('未登录');
		}
		// 获取客户端请求头的token
		const rawToken = String(author);
		tokenData = jwt.verify(rawToken, SECRET);
		console.log('Token Data:',tokenData);
		// 获取用户id
		const id = tokenData.id;
		const sesql = $sql.user.select + " where user_id = '" + id + "'";
		req.user = sqluser.getSql(sesql);
		next()
	}catch(err){
		console.error("【没有权限】\n")
		console.error(err);sep();
		next()
	}
}

module.exports = auth;